package com.trigsoft.applist;

import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

class ApplicationViewBinder implements SimpleCursorAdapter.ViewBinder
{
	private class LoadTask extends AsyncTask<Void, Void, Bitmap>
	{
		private ImageView view;
		private byte[] blob;
		private String name;

		public LoadTask(ImageView view, Cursor cursor, int columnIndex, String name)
		{
			this.view = view;
			blob = cursor.getBlob(columnIndex);
			this.name = name;
		}

		@Override
		protected Bitmap doInBackground(Void... arg0)
		{
			// TODO Auto-generated method stub
			return BitmapFactory.decodeByteArray(blob, 0, blob.length);
		}

		@Override
		protected void onPostExecute(Bitmap bitmap)
		{
			IconCache.icons.put(name, bitmap);
			view.setImageBitmap(bitmap);
		}
	}

	public boolean setViewValue(View view, Cursor cursor, int columnIndex)
	{
		String name = cursor.getString(cursor.getColumnIndex(DBHelper.KEY_LABEL));
		if (columnIndex == cursor.getColumnIndex(DBHelper.KEY_ICON))
		{
			if (IconCache.icons.containsKey(name))
			{
				((ImageView) view).setImageBitmap(IconCache.icons.get(name));
			} else
			{
				/*byte[] b = cursor.getBlob(columnIndex);
				Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
				IconCache.icons.put(name, bitmap);
				((ImageView) view).setImageBitmap(bitmap);*/
				new LoadTask((ImageView) view, cursor, columnIndex, name).execute();
			}
		} else if (columnIndex == cursor.getColumnIndex(DBHelper.KEY_LABEL))
		{

			((TextView) view).setText(name);
		}
		return true;
	}
}
